import React, { Component, PropTypes } from 'react';
import Echarts from 'echarts';
import { connect } from 'dva'
import {
  Input,
  Button,
  Select,
  Form,
  Modal,
  Row,
  Col,
  Icon,
  message,
} from 'antd';
import Style from './home.less';
import NumberPlay from '../../util/numberPlay';

import $ from 'jquery';
import Service from "../../service";
const FormItem = Form.Item;
const createForm = Form.create;
const Option = Select.Option;
import Moment from 'moment';
class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      soundflag: true,  // 消音
      soundUrl: '',
      soundUrl1: '',
      isexport: false,
      exportUrl: '',
      isType: ''
    };
  }
  componentDidMount() {
    let self = this;
    const token = localStorage.getItem('token');
    // this.props.queryStatistics({ token: token });
    let content = self.props.data;
    // console.log(content)
    if (content) {
      self.searchData(content.keywords)

    } else {
      message.error('未选择表中数据!', 1.5, function () {
        self.context.router.push(`/${self.props.routeParams.id}/app/mindex`)
      });
    }

  }
  componentWillUnmount() {
    if (this.state.timer != null) {
      clearInterval(this.state.timer);

    }
  }
  searchData = (value) => {
    let self = this;
    const token = localStorage.getItem('token');
    self.props.search({
      params: {
        keywords: value,
        token: token
      },
      func: function (data) {
        // console.log(data)
        if (data.type == 'today') {
          if (data.data) {
            if (data.data.export_url) {
              self.setState({
                isexport: true,
                exportUrl: data.data.export_url
              })
            }

            self.violationIndexFilter(data.data)
          } else {
            message.error('该关键词下无数据，请重新搜索', 1.5, function () {
              self.context.router.push(`/${self.props.routeParams.id}/app/AIManage`)
            })
          }

        } else if (data.type == 'file') {
          self.setState({
            isType: "file",
            fileUrl: data.file_path
          })
        } else if (data.type == 'violation') {
          if (data.data.pre_month_day_violation) {
            self.todayStaticsFilter(data.data.pre_month_day_violation)
          } else {
            message.error('该关键词下无数据，请重新搜索', 1.5, function () {
              self.context.router.push(`/${self.props.routeParams.id}/app/AIManage`)
            })
          }
        } else {
          if (data.data.eight_day_violation) {
            self.todayStaticsFilter(data.data.eight_day_violation)
          } else {
            message.error('该关键词下无数据，请重新搜索', 1.5, function () {
              self.context.router.push(`/${self.props.routeParams.id}/app/AIManage`)
            })
          }


        }
        self.setState({
          soundUrl: data.mp3,
          soundUrl1: data.mp3,
          soundflag: true
        })

      }
    });
  }

  mindexurlFun = () => {
    this.context.router.push(`/1/app/mindex`);
  }
  mapurlFun = () => {
    this.context.router.push(`/1/app/mmap`);
  }
  myurlFun = () => {
    this.context.router.push(`/1/app/mmy`);
  }
  messageUrlFun = () => {
    this.context.router.push(`/1/app/mmessage`);
  }

  // 搜索值
  searchValueFun = (e) => {
    this.setState({
      searchKeywords: e.target.value
    })
  }
  // 搜索
  searchFun = (e) => {
    let self = this;
    const token = localStorage.getItem('token');
    let value = this.state.searchKeywords;
    if (!value) {
      message.error('请输入搜索的值', 1.5);
      return false;
    }
    //    console.log(value)

    self.props.search({
      params: {
        keywords: value,
        token: token
      },
      func: function (data) {
        self.props.saveSelect({ 'keywords': value })
        self.context.router.push(`/${self.props.routeParams.id}/app/maidetail`)

      }
    });

  }
  // 搜索
  searchFun = (e) => {
    // const token = localStorage.getItem('token');
    this.setState({
      searchKeywords: e.target.value
    })
    // this.props.queryList({ token: token, page: 1, page_size: 15, realname: value })
  }
  violationIndexFilter = (data) => {
    let self = this;
    let vData = [];
    let bData = ['在途量', '注册量', '车总量'];
    vData.push(data.running_total);
    vData.push(data.user_total);
    vData.push(data.ebike_total);
    self.violationIndexFun(bData, vData);
  }
  // 柱状图  违章用曲线图 今日数据用柱状图吧
  violationIndexFun = (bData, vData) => {
    // console.log(labelData)
    // 基于准备好的dom，初始化echarts实例
    let staticsRegionWrap = document.getElementById('violationIndexWrap1');
    if (!staticsRegionWrap) {
      return false
    }
    let staticsRegionChart = echarts.init(staticsRegionWrap);
    // 绘制图表
    staticsRegionChart.setOption({
      title: {
        subtext: '100(百分比)',
        "x": "50px"
      },
      grid: {
        x: 80,
        y: 35,
        x2: 80,
        y2: 25,
      },
      xAxis: {
        type: 'category',
        data: bData,
        axisLine: {
          lineStyle: {
            color: '#3e3e3e',
            width: 1
          }
        }
      },
      yAxis: {
        type: 'value',
        axisLine: {
          // splitArea: { show: true },//保留网格区域
          lineStyle: {
            color: '#999999',
            width: 1
          }
        }
      },
      series: [{
        data: vData,
        type: 'bar',
        //设置柱子的宽度
        barWidth: 15,
        //配置样式
        itemStyle: {
          //通常情况下：
          normal: {
            //每个柱子的颜色即为colorList数组里的每一项，如果柱子数目多于colorList的长度，则柱子颜色循环使用该数组
            color: function (params) {
              var colorList = ['#52d6ff', '#d82727', '#0c3b95', '#afff00', '#ff7900'];
              return colorList[params.dataIndex];
            }
          },
          //鼠标悬停时：
          emphasis: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
      }]
    });
  }
  todayStaticsFilter = (data) => {
    let self = this;
    let vData = [];
    let bData = [];
    for (let i = 0; i < data.length; i++) {
      let v = data[i].value.substr(0, data[i].value.length - 1);
      bData.push(data[i].date);
      vData.push(v)
    }
    self.todayStaticsFun(bData, vData);
  }
  // 违章折现图
  todayStaticsFun = (bData, vData) => {
    // console.log(labelData)
    // 基于准备好的dom，初始化echarts实例
    let staticsRegionWrap = document.getElementById('violationIndexWrap1');
    if (!staticsRegionWrap) {
      return false
    }
    let staticsRegionChart = echarts.init(staticsRegionWrap);
    // 绘制图表
    staticsRegionChart.setOption({
      title: {
        subtext: '100(百分比)  -违章率',
      },
      grid: {
        x: 30,
        y: 35,
        x2: 40,
        y2: 35,
      },
      xAxis: {
        type: 'category',
        data: bData,
      },
      yAxis: {
        type: 'value'
      },
      series: [{
        data: vData,
        type: 'line',
        itemStyle: {
          normal: {
            color: "#64BBFC",//折线点的颜色
            lineStyle: {
              color: "#64BBFC",//折线的颜色
              width: 1// 0.1的线条是非常细的了
            },

          }
        }
      }]
    });
  }
  bf = () => {
    var audio = document.getElementById('music1');
    if (audio !== null) {
      //检测播放是否已暂停.audio.paused 在播放器播放时返回false.
      // alert(audio.paused);
      if (audio.paused) {
        audio.play();//audio.play();// 这个就是播放  
      } else {
        audio.pause();// 这个就是暂停
      }
    }
  }
  returnFun = () => {
    this.context.router.push(`/1/app/mindex`);
  }
  // 导出数据
  exportFun = () => {
    let exportUrl = this.state.exportUrl;
    if (exportUrl) {
      window.location.href = exportUrl;
    }
  }
  // 下载文件
  fileFun = () => {
    let fileUrl = this.state.fileUrl;
    if (fileUrl) {
      window.location.href = fileUrl;
    }
  }
  render() {
    const { detailData } = this.state;
    // console.log(systemData);
    // console.log(this.props);
    return (
      <div className={Style.wrapH100 + ' ' + Style.wrap}>
        <div className={Style.headWrap}>
          <div className={Style.navTitle}>
            <span className={Style.arrow} onClick={this.returnFun}>
              <Icon type="left" />
            </span>
            AI系统
           <span className={Style.arrowEdit} onClick={this.messageUrlFun}><em className={Style.bellIcon}></em></span>
          </div>
        </div>
        <div className={Style.staticWrap}>
          {this.state.isexport &&
            <Button style={{ marginBottom: '20px' }} type="primary" onClick={this.exportFun}>导出数据</Button>
          }
          {this.state.isType == 'file' &&
            <Button style={{ marginBottom: '20px' }} type="primary" onClick={this.fileFun}>下载文件</Button>
          }
          {this.state.isType != 'file' &&
            <div className={Style.staticsCon + ' ' + Style.companyTopCon}>
              <div className={Style.staticoneWrap} id="violationIndexWrap1">

              </div>
            </div>
          }
          <div className={Style.staticsCon + ' ' + Style.companyTopCon}>
            <div className={Style.staticoneWrap} id="violationIndexWrap1">

            </div>
          </div>
          <Button style={{ marginTop: '20px' }} type="primary" onClick={this.bf}>暂停播放</Button>
        </div>


        {this.state.isType != 'file' && this.state.soundflag &&
          <div id="alarmsound" >
            {
              this.state.soundUrl &&
              <audio autoPlay id='music1'>
                <source src={this.state.soundUrl} type='audio/mp3' />
                <embed src={this.state.soundUrl} type='audio/mpeg' autostart='true' loop='1' />
              </audio>
            }

          </div>
        }
        <div className={Style.foot}>
          <Row type="flex">
            <Col span={8} order={1} className={Style.on} onClick={this.mindexurlFun}>
              <Icon style={{ fontSize: 20 }} type="line-chart" theme="outlined" /><p>AI系统</p>
            </Col>
            <Col span={8} order={2} onClick={this.mapurlFun}>
              <Icon style={{ fontSize: 20 }} type="environment" theme="outlined" /><p>大屏地图</p>
            </Col>
            <Col span={8} order={2} onClick={this.myurlFun}>
              <Icon style={{ fontSize: 20 }} type="user" theme="outlined" /><p>我的</p>
            </Col>
          </Row>
        </div>
        <div className={Style.marsk} style={{ display: this.state.loading }}>
          <Icon type="loading" className={Style.loading} />
          <p className={Style.loadText}>请耐心等待...</p>
        </div>
      </div>
    )
  }
}

App.contextTypes = {
  router: React.PropTypes.object
}

function mapStateToProps(state, ownProps) {
  // console.log(state)
  return {
    data: state.mmodel.saveSeslect,
    loading: !!state.loading.global,

  }
}

function dispatchToProps(dispatch) {
  return {
    search(payload = {}) {
      dispatch({ type: 'mmodel/serch', payload })
    },
    receive(payload, params) {
      dispatch({ type: 'mmodel/receive', payload })
    },

  }
}
export default connect(mapStateToProps, dispatchToProps)(Form.create()(App));
